"""
下载图片
"""
import facade
from xjlibrary.our_file_dir import BaseDir, ImageFile

curpath = BaseDir.get_file_dir_absolute(__file__)
TopPath = BaseDir.get_upper_dir(curpath, -2)
configfile = BaseDir.get_new_path(curpath, "db.ini")
dirPath = BaseDir.get_new_path(TopPath, "download", "intlpress", "download", "cover")
BaseDir.create_dir(dirPath)


class DownCover(object):
    def __init__(self):
        self.logger = facade.get_streamlogger()
        self.mysqlutils = facade.MysqlUtiles(configfile, "db", logger=self.logger)
        self.baseurl = "https://www.intlpress.com/"

    def select(self):
        sql = "select coverurl,jid from journal where types='journals' and coverstat=0"
        rows = self.mysqlutils.SelectFromDB(sql)
        for row in rows:
            fullurl = self.baseurl + row[0]
            BoolResult, errString, r = facade.BaseRequest(fullurl, endstring="", timeout=(30, 60))
            if BoolResult:
                if self.save_file(row[1], r.content):
                    sql = "update journal set coverstat=1 where jid='{}'".format(row[1])
                    self.mysqlutils.ExeSqlToDB(sql)
            else:
                self.logger.info("下载失败")

    def save_file(self, rawid, content):
        name = rawid.lower() + ".jpg"
        if ImageFile.img_to_format_jpg(content, BaseDir.get_new_path(dirPath, name)):
            self.logger.info("图片保存成功")
            return True
        return False


def main():
    down = DownCover()
    down.select()


if __name__ == "__main__":
    main()
